import asyncio
from typing import Any, Dict, Optional
from fastapi import FastAPI
from models.model_manager import ModelManager
from config import MODEL_CONFIG
from utils.logger import setup_logger

logger = setup_logger()
# 全局应用状态实例
_app_state = None
_app_state_lock = asyncio.Lock()

class AppState:
    """应用程序状态类，用于存储和管理模型实例"""
    def __init__(self):
        self.models = {}
        # 这些属性将由model_manager动态添加
        # self.ollama_client = None
        # self.whisper_model = None
        # self.chattts_model = None
        # self.whisperx_model = None

async def get_app_state() -> Any:
    """获取全局应用状态实例，如果不存在则创建"""
    global _app_state
    
    async with _app_state_lock:
        if _app_state is None:
            _app_state = AppState()
            # 初始化模型管理器
            model_manager = ModelManager()
            
            # 预加载常用模型
            try:
                # 预加载ollama模型，确保ollama_client属性存在
                await model_manager.load_model("ollama", _app_state, {"config": {"ollama_chat_model": "deepseek-r1:7b","ollama_host":"http://localhost:11434"}})
                logger.info("Ollama模型已预加载")
            except Exception as e:
                logger.error(f"预加载模型时出错: {str(e)}")
        elif not hasattr(_app_state, 'ollama_client') or _app_state.ollama_client is None:
            # 如果app_state存在但ollama_client不存在，重新加载ollama模型
            try:
                model_manager = ModelManager()
                await model_manager.load_model("ollama", _app_state, {"config": {"model_name": "deepseek-r1:7b"}})
                logger.info("Ollama模型已重新加载")
            except Exception as e:
                logger.error(f"重新加载ollama模型时出错: {str(e)}")
        
        return _app_state

# 在FastAPI应用启动时初始化应用状态
def init_app_state(app: FastAPI):
    """初始化应用状态并附加到FastAPI应用"""
    @app.on_event("startup")
    async def startup_event():
        app.state = await get_app_state()
        print("应用状态已初始化")
    
    @app.on_event("shutdown")
    async def shutdown_event():
        # 清理资源
        model_manager = ModelManager()
        for model_name in model_manager.status:
            model_manager.unload_model(model_name, app.state)
        print("应用状态已清理")